/*
 *  GWTurntableStopEffect.cpp
 *  GWGlitch
 *
 *  Created by Michael Forrest on 28/02/2008.
 *  Copyright 2008 Grimaceworks. All rights reserved.
 *
 */

#include "GWTurntableStopEffect.h"

void GWTurntableStopEffect::Init(){
	mSampleRate = kernel->GetSampleRate();
	
	MIN_STOP_RATE = 0.9;
	MAX_STOP_RATE = 0.99;
	Reset();
}
void GWTurntableStopEffect::Reset(){
	mLastRecordedPosition = 0;
	mLastPlaybackPosition = 0;
	mCurrentSpeed = 1;
}
void GWTurntableStopEffect::Process(const Float32 *inSourceP,
								Float32		*inDestP,  
								UInt32 		inFramesToProcess,  
								UInt32		inNumChannels,  
								bool		&ioSilence){
	
	UInt32 nSampleFrames = inFramesToProcess;
	const Float32 *sourceP = inSourceP;
	Float32 *destP = inDestP;
	
	
	Float32 friction =  1 - kernel->GetParameter(kParam_TurntableFriction)/100;
	Float32 stopRate = MIN_STOP_RATE + ( (MAX_STOP_RATE-MIN_STOP_RATE) * (friction));
	

	while (nSampleFrames-- >0){
		Float32 inputSample = *sourceP;
		mSampleLoop[mLastRecordedPosition] = inputSample; // change this to use a pointer member variable to stop doing a lookup each time
		mLastRecordedPosition ++;
		if(mLastRecordedPosition >= loopSize) mLastRecordedPosition = 0;
		sourceP += inNumChannels;
	}
	nSampleFrames = inFramesToProcess; // reset iterator
	// apply transformation
	while (nSampleFrames-- > 0) {
		Float32 outputSample;
		if(mCurrentSpeed < 0.001) {
			outputSample = mLastSampleValue * 0.9; // should interpolate to 0 to avoid click

		}else{
			int lastPlaybackPos = (int)(mLastPlaybackPosition);// previous value
			Float32 lastSampleValue = mSampleLoop[lastPlaybackPos ];
			Float32 nextSampleValue = mSampleLoop[lastPlaybackPos+1];
			outputSample = lastSampleValue + ((nextSampleValue - lastSampleValue) * (mLastPlaybackPosition - (int) mLastPlaybackPosition)); // this interpolation could be optimised
			
			mLastPlaybackPosition += mCurrentSpeed;
		}
		mLastSampleValue = outputSample;
		*destP = outputSample;
		destP += inNumChannels;
	}
	mCurrentSpeed *= stopRate;
	//printf("stopRate= %f, sampleRate=%f, nFrames=%i\n", stopRate,mSampleRate,(int)inFramesToProcess);
	
} 